import { useEffect, useState } from 'react';
import { Table, Empty, Message } from '@arco-design/web-react';
import { CardDetailWalletRefundApply } from './types';
import main from '../../../main';
import DetailModal from '../../../components/detailModal';
import { dictTag, keepCopy } from '../../../components/tableColumn';
import { getDict } from '../../../utils/utils';
import { apiGetCardDetailWalletLogList } from './api';
import LoadingMask from '../../../components/loadingMask';

interface Props {
  iccid?: string | undefined;
  cardWalletLog?: boolean;
  onCancel: () => void;
}

// 状态
const CARD_DETAIL_WALLET_LOG_BUSINESS_TYPE = 'card_detail_wallet_log_business_type';
export default function CardWalletLogDialog({ iccid, cardWalletLog, onCancel }: Props) {
  const [list, setList] = useState<CardDetailWalletRefundApply[]>([]);
  const [fetching, setFetching] = useState(false);
  const [loaded, setLoaded] = useState(false);
  // 每页条数
  const [pageSize, setPageSize] = useState(main.defaultPageSize);
  // 当前页数
  const [pageNum, setPageNum] = useState(1);
  // 总页数
  const [total, setTotal] = useState();
  const [dictDatas, setDictDatas] = useState<Record<string, any>>({});
  useEffect(() => {
    async function fetchDictData() {
      const data = await getDict(CARD_DETAIL_WALLET_LOG_BUSINESS_TYPE);
      setDictDatas(data);
    }
    fetchDictData();
  }, []); //eslint-disable-line
  useEffect(() => {
    getWalletLogList();
  }, []); //eslint-disable-line

  // 获取列表接口
  async function getWalletLogList(num?: number, size?: number) {
    LoadingMask.show('正在加载...');
    try {
      let res = await apiGetCardDetailWalletLogList(num ?? pageNum, size ?? pageSize, {
        iccid,
      });
      let data = res.data;
      if (!loaded) {
        setLoaded(true);
      }
      if (data.code === 200) {
        if (fetching) {
          setFetching(false);
        }
        if (!loaded) {
          setLoaded(true);
        }
        setTotal(data.total);
        setList(data.rows ?? []);
      } else {
        Message.warning(data.msg ?? '加载失败');
        setList([]);
      }
    } catch (e: any) {
      Message.error(e.messag ?? '加载失败');
    } finally {
      LoadingMask.hide();
    }
  }

  /**
   * 分页器 切换分页和条数
   * @param page 当前页数
   * @param size 每页条数
   */
  function handlePageAndSizeChange(page: number, size: number) {
    if (page === pageNum && size === pageSize) return;
    setPageSize(size);
    setPageNum(page);
    getWalletLogList(page, size);
  }

  let dataSource = (list || []).map((item) => Object.assign({}, item, { key: item.id }));

  // 定义类型表格内的列
  const dataColumns = [
    {
      title: '充值卡号',
      dataIndex: 'iccid',
      key: 'iccid',
      render: keepCopy,
    },
    {
      title: '业务类型',
      dataIndex: 'businessType',
      key: 'businessType',
      render: (v: string) => dictTag(v, dictDatas[CARD_DETAIL_WALLET_LOG_BUSINESS_TYPE]),
    },
    {
      title: '原有金额',
      dataIndex: 'availableAmountSource',
      key: 'availableAmountSource',
    },
    {
      title: '加减金额',
      dataIndex: 'availableAmountOperation',
      key: 'availableAmountOperation',
    },
    {
      title: '当前余额',
      dataIndex: 'availableAmountTarget',
      key: 'availableAmountTarget',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
    },
  ];
  return (
    <DetailModal
      show={cardWalletLog}
      title="充消记录"
      cancelBtnShow={false}
      onConfirm={onCancel}
      onCancel={onCancel}
      className="bw-80"
      contentClassName="h-500"
    >
      <Table
        className="bw-100"
        data={dataSource}
        columns={dataColumns}
        pagination={{
          className: 'pagination-block',
          total: total || 1,
          current: pageNum,
          pageSize: pageSize,
          showJumper: true,
          sizeCanChange: true,
          sizeOptions: main.defaultPageSizeOptions,
          showTotal: (total) => `共${total}条`,
          size: 'small',
          onChange: handlePageAndSizeChange,
        }}
        loading={!list || (fetching && !loaded)}
        noDataElement={<Empty description="暂无数据" />}
      />
    </DetailModal>
  );
}
